﻿namespace Groundwork.Core
{
    using System;
    using System.Threading;

    public class GenericUtility
    {
        /// <summary>
        /// Executes a series of Action Delegates in the order that they are provided.
        /// </summary>
        /// <param name="args">a list of action delegates</param>
        public void ExecuteInSequence(params Action[] args)
        {
            if (args != null)
            {
                try
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        args[i]();
                    }
                }
                catch
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// Allows you to default an input value
        /// </summary>
        /// <typeparam name="T">Type that you want to be returned</typeparam>
        /// <param name="inputValue">input value that you want to test and default it necessary</param>
        /// <param name="defaultValue">the default value to use</param>
        /// <returns>either the input value or the defaut value converted to type T</returns>
        public static T DefaultIfNull<T>(object inputValue, T defaultValue)
        {
            try
            {
                if (inputValue != null)
                {
                    return (T)Convert.ChangeType(inputValue, typeof(T), Thread.CurrentThread.CurrentCulture);
                }
                else
                {
                    return defaultValue;
                }
            }
            catch
            {
                throw new InvalidOperationException("Unable to perform default operation");
            }
        }

        /// <summary>
        /// Returns the first non-null value in the provided argument array
        /// </summary>
        /// <typeparam name="T">Type to convert found object to</typeparam>
        /// <param name="args">argument array</param>
        /// <returns>found value</returns>
        public static T FirstNoneNull<T>(params object[] args) where T : IConvertible
        {
            if (args != null)
            {
                for (int index = 0; index < args.Length; index++)
                {
                    if (args[index] != null)
                    {
                        return (T)Convert.ChangeType(args[index], typeof(T));
                    }
                }
            }

            return default(T);
        }

        public static void DelayedExecute(int seconds, Action operation)
        {
            Timer delayTimer = new Timer(
                (o) => 
                { 
                    operation(); 
                },
                null, 
                TimeSpan.FromSeconds(seconds).Milliseconds, 
                System.Threading.Timeout.Infinite);
        }



    }
}
